<?php
namespace App\Http\Controllers\Admin;

use AntChain\ATO\Models\GoodsInfo;
use App\Models\AppletsIndex;
use App\Models\AppletsIndexGoodsList;
use App\Models\AppletsIndexListCategory;
use App\Models\Goods;
use App\Models\GoodsSetmeal;
use App\Services\CommonService;
use App\Services\GoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AlipayIndexController  extends BaseController
{

    /**
     * 保存数据
     * @param Request $request
     * @return false|string
     */
    public function setIndex(Request $request){
//        $params = $request->input('params');
//        $params=json_decode($params,true);
//        dd($params);
        try {
            $type = $request->input('type');
            $status = $request->input('status');
            $params = $request->input('params');
            if(!$type || !$status || !$params){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $params=json_decode($params,true);
            if($type=='6'){
                foreach ($params['one']['goods'] as &$good) {
                    $goods=Goods::where(['id'=>$good['goods_id']])->first();
                    $buyout_price= GoodsSetmeal::where(['goods_id'=>$good['goods_id'],'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                    if($goods['min_price']&&$goods['min_lease_term']&&$buyout_price){
                        $good['price'] = bcsub($goods['min_price'],$buyout_price/$goods['min_lease_term'],2);
                    }
                }
                foreach ($params['two']['goods'] as &$good) {
                    $goods=Goods::where(['id'=>$good['goods_id']])->first();
                    $buyout_price= GoodsSetmeal::where(['goods_id'=>$good['goods_id'],'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                    if($goods['min_price']&&$goods['min_lease_term']&&$buyout_price){
                        $good['price'] = bcsub($goods['min_price'],$buyout_price/$goods['min_lease_term'],2);
                    }
                }
            }else if($type==9){
                foreach ($params[0]['goods'] as &$good) {
                    $goods=Goods::where(['id'=>$good['goods_id']])->first();
                    $buyout_price= GoodsSetmeal::where(['goods_id'=>$good['goods_id'],'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                    if($goods['min_price']&&$goods['min_lease_term']&&$buyout_price){
                        $good['price'] = bcsub($goods['min_price'],$buyout_price/$goods['min_lease_term'],2);
                    }
                }
            }else{
                if($params['goods']){
                    foreach ($params['goods'] as &$good) {
                        $goods=Goods::where(['id'=>$good['goods_id']])->first();
                        $buyout_price= GoodsSetmeal::where(['goods_id'=>$good['goods_id'],'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                        if($goods['min_price']&&$goods['min_lease_term']&&$buyout_price){
                            $good['price'] = bcsub($goods['min_price'],$buyout_price/$goods['min_lease_term'],2);
                        }
                    }
                }
            }

            $params=json_encode($params);

            $count = AppletsIndex::where(['type'=>$type])->count();
            $data = [
                'type'=>$type,
                'status'=>$status,
                'params'=>$params,
                'is_release'=>AppletsIndex::RELEASE_ONLINE_NOT,
            ];
            if($count > 0){
                AppletsIndex::where(['type'=>$type])->update($data);
            }else{
                AppletsIndex::where(['type'=>$type])->insert($data);
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'保存成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'保存失败');
        }
    }

    /**
     * 查找单个分类数据
     * @param Request $request
     * @return false|string
     */
    public function findInfo(Request $request){
        $type = $request->input('type');
        if(!$type){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        $indexData = AppletsIndex::where(['type'=>$type])->select('id','status','params')->first();
        $indexData = obToArray($indexData);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$indexData);
    }

    /**
     * 获取预览数据
     * @param Request $request
     * @return false|string
     */
    public function preview(Request $request){
        $indexData = AppletsIndex::where(['status'=>AppletsIndex::STATUS_YES_SHOW])->orderBy('type','asc')->get();
        $indexData = obToArray($indexData);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$indexData);
    }

    /**
     * 发布上线
     * @param Request $request
     * @return false|string
     */
    public function releaseOnline(Request $request){
        try {
            //更改发布状态
            AppletsIndex::where(['status'=>AppletsIndex::STATUS_YES_SHOW,'is_release'=>AppletsIndex::RELEASE_ONLINE_NOT])->update(['is_release'=>AppletsIndex::RELEASE_ONLINE_YES]);

            $indexData = AppletsIndex::where(['status'=>AppletsIndex::STATUS_YES_SHOW,'is_release'=>AppletsIndex::RELEASE_ONLINE_YES])->orderBy('type','asc')->get();
            $indexData = obToArray($indexData);
            if(!$indexData){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'发布数据为空');
            }
            $data = [];
            foreach ($indexData as $item){
                $data[$item['type']] = $item['params'];
            }
            $addData = [
                'params'=>json_encode($data),
                'is_release'=>AppletsIndex::RELEASE_ONLINE,
            ];
            $count = AppletsIndex::where(['is_release'=>AppletsIndex::RELEASE_ONLINE])->count();
            if($count > 0){
                AppletsIndex::where(['is_release'=>AppletsIndex::RELEASE_ONLINE])->update($addData);
            }else{
                AppletsIndex::insert($addData);
            }
            //设置缓存
            $pageSize = AppletsIndex::CACHE_LIMIT_NUM;
            $limit = intval(ceil(count($data)/$pageSize));
            for ($i=1;$i<=$limit;$i++){
                $request->merge(['page' => $i]);
                $limitData = AppletsIndex::where(['status'=>AppletsIndex::STATUS_YES_SHOW,'is_release'=>AppletsIndex::RELEASE_ONLINE_YES])
                    ->orderBy('type','asc')
                    ->paginate($pageSize);
                $limitData = obToArray($limitData);
                if($limitData){
                    Redis::hset(AppletsIndex::REDIS_KEY,$i,json_encode($limitData));
                }
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'发布成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,$exception->getMessage());
        }
    }

    /**
     * 精选分类列表
     * @param Request $request
     * @return false|string
     */
    public function categoryList(Request $request){
        $name = $request->input('name','');
        $status = $request->input('status','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $where= [
            ['is_delete',CommonService::IS_DELETE_NOT],
        ];
        if($name){
            $where[] = ['name','like','%'.$name.'%'];
        }
        if($status){
            $where[] = ['status',$status];
        }
        $category = AppletsIndexListCategory::where($where)
            ->orderBy('sort','asc')
            ->orderBy('id','asc')
            ->paginate($pageSize);
        $category = obToArray($category);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$category);
    }

    /**
     * 添加精选分类
     * @param Request $request
     * @return false|string
     */
    public function addCategory(Request $request){
        try {
            $name = $request->input('name');
            $title = $request->input('title');
            $status = $request->input('status');
            if(!$name || !$title || !$status){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $data = [
                'name'=>$name,
                'status'=>$status,
                'title'=>$title,
                'create_time'=>dateFormat(time()),
            ];
            AppletsIndexListCategory::insert($data);
            //设置分类缓存
            $this->setCategoryCache();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'保存成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,$exception->getMessage());
        }
    }

    /**
     * 编辑精选分类
     * @param Request $request
     * @return false|string
     */
    public function editCategory(Request $request){
        try {
            $id = $request->input('id');
            $name = $request->input('name');
            $title = $request->input('title');
            $status = $request->input('status');
            if(!$id || !$name || !$title || !$status){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $data = [
                'name'=>$name,
                'status'=>$status,
                'title'=>$title,
            ];
            AppletsIndexListCategory::where(['id'=>$id])->update($data);
            //设置分类缓存
            $this->setCategoryCache();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'编辑失败');
        }
    }

    /**
     * 设置精选分类 排序
     * @param Request $request
     * @return false|string
     */
    public function setCategorySort(Request $request){
        try {
            $id = $request->input('id');
            $sort = $request->input('sort','0');
            if(!$id){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $data = [
                'sort'=>$sort,
            ];
            AppletsIndexListCategory::where(['id'=>$id])->update($data);
            //设置分类缓存
            $this->setCategoryCache();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'编辑失败');
        }
    }
    /**
     * 设置精选分类 状态
     * @param Request $request
     * @return false|string
     */
    public function setCategoryStatus(Request $request){
        try {
            $id = $request->input('id');
            $status = $request->input('status',AppletsIndexListCategory::STATUS_NOT_SHOW);
            if(!$id){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $data = [
                'status'=>$status,
            ];
            AppletsIndexListCategory::where(['id'=>$id])->update($data);
            //设置分类缓存
            $this->setCategoryCache();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'编辑失败');
        }
    }

    /**
     * 删除 精选分类
     * @param Request $request
     * @return false|string
     */
    public function setCategoryDel(Request $request){
        try {
            $id = $request->input('id');
            if(!$id){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $check = AppletsIndexGoodsList::where(['list_cate_id'=>$id,'status'=>AppletsIndexGoodsList::STATUS_YES_SHOW])->first();
            if($check){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'分类包含上架推广商品，无法删除');
            }
            $data = [
                'is_delete'=>CommonService::IS_DELETE_YES,
            ];
            AppletsIndexListCategory::where(['id'=>$id])->update($data);
            //设置分类缓存
            $this->setCategoryCache();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'删除成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'删除失败');
        }
    }


    /**
     * 推广分类-精选分类列表
     * @param Request $request
     * @return false|string
     */
    public function listCategoryList(){
        $category = AppletsIndexListCategory::getList();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$category);
    }


    /**
     * 推广列表数据添加
     * @param Request $request
     * @return false|string
     */
    public function addList(Request $request){
        try {
            $goodsId = $request->input('goodsId');
            $listCateId = $request->input('listCateId');
            if(!$goodsId){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $goodsInfo = Goods::where(['id'=>$goodsId,'is_delete'=>GoodsService::GOODS_NO_DELETE_STATUS,'status'=>GoodsService::GOODS_STATUS_PUT])
                ->first();
            $goodsInfo = obToArray($goodsInfo);
            if(!$goodsInfo){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'商品不存在或已下架');
            }
            $checkGoods = AppletsIndexGoodsList::where(['goods_id'=>$goodsId,'list_cate_id'=>$listCateId])->first();
            if($checkGoods){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'商品已添加推广列表');
            }
            $data = [
                'goods_id'=>$goodsId,
                'list_cate_id'=>$listCateId,
                'category_id'=>$goodsInfo['category_id'],
                'member_id'=>$goodsInfo['member_id'],
                'create_time'=>dateFormat(time()),
                'shelves_time' => dateFormat(time()),
            ];
            AppletsIndexGoodsList::insert($data);
            $this->setListCache($listCateId);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'添加成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'添加失败');
        }
    }

    /**
     * 首页推荐列表
     * @param Request $request
     * @return false|string
     */
    public function goodsList(Request $request){
        $listCateId = $request->input('listCateId','');
        $goodsName = $request->input('goodsName','');
        $shopName = $request->input('shopName','');
        $categoryId = $request->input('categoryId','');
        $status = $request->input('status','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        if(!$listCateId){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $where= [
            ['list.list_cate_id',$listCateId],
            ['category.status',AppletsIndexListCategory::STATUS_YES_SHOW],
            ['g.is_delete',GoodsService::GOODS_NO_DELETE_STATUS],
            ['g.status',GoodsService::GOODS_STATUS_PUT],
        ];

        if($categoryId){
            $where[] = ['c.id',$categoryId];
        }
        if($goodsName){
            $where[] = ['g.title','like','%'.$goodsName.'%'];
        }
        if($shopName){
            $where[] = ['su.shopname','like','%'.$shopName.'%'];
        }
        if($status==1){
            $where[] = ['list.status',2];
        }

        if($status==2){
            $where[] = ['list.status',1];
        }

        $list = AppletsIndexGoodsList::from('sp_index_goods_list as list')
            ->select(['list.id','list.sort','list.shelves_time','list.status','su.shopname','c.name as category_name','g.id as goods_id','g.title','g.imgurl'])
            ->leftjoin('sp_index_list_category as category', 'category.id', 'list.list_cate_id')
            ->leftjoin('sp_goods_2 as g', 'g.id', '=', 'list.goods_id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', '=', 'list.member_id')
            ->leftjoin('sp_category as c', 'c.id', '=', 'list.category_id')
            ->where($where)
            ->orderBy('list.sort','asc')
            ->paginate($pageSize);
        $list = obToArray($list);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 设置推广列表数据状态
     * @param Request $request
     * @return false|string
     */
    public function setListStatus(Request $request){
        try {
            $id = $request->input('id');
            $status = $request->input('status');
            if(!$id || !$status){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $goodsList = AppletsIndexGoodsList::where(['id'=>$id])->first();
            $goodsList = obToArray($goodsList);
            if(!$goodsList){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'数据不存在');
            }
            $updateData['status'] = $status;
            if($status == AppletsIndexGoodsList::STATUS_YES_SHOW){
                $updateData['shelves_time'] = dateFormat(time());
            }
            AppletsIndexGoodsList::where(['id'=>$id])->update($updateData);
            $this->setListCache($goodsList['list_cate_id']);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'编辑失败');
        }
    }

    /**
     * 设置推广列表数据排序
     * @param Request $request
     * @return false|string
     */
    public function setListSort(Request $request){
        try {
            $id = $request->input('id');
            $sort = $request->input('sort');
            if(!$id){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $goodsList = AppletsIndexGoodsList::where(['id'=>$id])->first();
            $goodsList = obToArray($goodsList);
            if(!$goodsList){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'数据不存在');
            }
            AppletsIndexGoodsList::where(['id'=>$id])->update(['sort'=>$sort]);
            $this->setListCache($goodsList['list_cate_id']);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功');
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'编辑失败');
        }
    }

    /**
     * 设置首页列表缓存
     * @param $categoryId
     */
    private function setListCache($categoryId){

        $data = AppletsIndexGoodsList::where(['list_cate_id'=>$categoryId,'status'=>AppletsIndexGoodsList::STATUS_YES_SHOW])->count();
        //设置缓存
        $pageSize = AppletsIndexGoodsList::CACHE_LIMIT_NUM;
        $limit = intval(ceil($data/$pageSize));
        for ($i=1;$i<=$limit;$i++){
            $page = $i;
            $limitData = AppletsIndexGoodsList::getList($categoryId,$page,$pageSize);
            if($limitData){
                Redis::hset(AppletsIndexGoodsList::REDIS_LIST_KEY,$categoryId.'-'.$page,json_encode($limitData));
            }
        }
    }

    /**
     * 设置分类缓存
     */
    private function setCategoryCache(){
        //设置所有分类缓存
        $category = AppletsIndexListCategory::getList();
        Redis::set(AppletsIndexListCategory::REDIS_CATEGORY_KEY,json_encode($category));
        //设置排序第一个分类缓存
        $firstCategory = AppletsIndexListCategory::getFirstList();
        Redis::set(AppletsIndexListCategory::REDIS_FIRST_CATEGORY_KEY,json_encode($firstCategory));
    }

    /**
     * 选择商品
     */
    public function chooseGoods(Request $request){
        $cate_id = $request->input('cate_id');
        $goods_name = $request->input('goods_name','');
        $shop_name = $request->input('shop_name','');
        $list_cate_id = $request->input('list_cate_id','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',12);
        if(!$list_cate_id){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请先设置推荐分类');
        }
        $where[]= ['g.status',GoodsService::GOODS_STATUS_PUT];
        if($cate_id){
            $where[] = ['g.category_id',$cate_id];
        }
        if($shop_name){
            $where[] = ['s.shopname',$shop_name];
        }
        $list = Goods::GetGoodsListAndCategory($where,$goods_name, $page, $pageSize);
        if($list){
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['pact_type'] = GoodsService::getGoodsPactName($v['pact_type']);
                $checkGoods = AppletsIndexGoodsList::where(['list_cate_id'=>$list_cate_id,'goods_id'=>$v['goods_id']])->first();
                $list['data'][$k]['is_choose'] = $checkGoods ? AppletsIndexGoodsList::ACTIVITY_NOT : AppletsIndexGoodsList::ACTIVITY_YES;
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }



}


